package com.base.component.ai.workflow.handle;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.base.component.ai.agent.bo.ContextBO;
import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.agent.core.base.Agent;
import com.base.component.ai.workflow.core.NodeHandle;
import com.base.component.ai.workflow.flow.Flow;
import com.base.component.ai.workflow.logs.NodeLog;
import com.base.component.ai.workflow.logs.NodeLogAgent;
import com.base.component.ai.workflow.node.Node;
import com.base.component.ai.workflow.node.NodeAgent;
import com.base.core.context.utils.SpringUtils;
import com.gitee.magic.framework.base.utils.MapConvert;

@Component
public class NodeHandleAgent<MSG,AP extends ContextParamBO,PP> implements NodeHandle<MSG,AP,PP>{

	@Override
	public <T extends Node> boolean support(Class<T> cls) {
		return cls.equals(NodeAgent.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T extends Node>List<Flow> execute(ContextBO<MSG,AP,PP> context,Map<String,Object> params,Flow flow,T node,Consumer<NodeLog> c) {
		NodeAgent d=(NodeAgent)node;
		Agent<MSG,AP,PP> agent=(Agent<MSG,AP,PP>)SpringUtils.getBean(d.getBeanName());
		agent.apply(context);
		if(!CollectionUtils.isEmpty(d.getContextParamInjects())) {
			Map<String,Object> contextParamMap=MapConvert.convert(context.getContextParam());
			for(String name:d.getContextParamInjects()) {
				params.put(name, contextParamMap.get(name));
			}
		}
		if(!CollectionUtils.isEmpty(d.getPromptParamInjects())) {
			Map<String,Object> promptParamMap=MapConvert.convert(context.getPromptParam());
			for(String name:d.getPromptParamInjects()) {
				params.put(name, promptParamMap.get(name));
			}
		}
		
		NodeLogAgent<MSG,AP,PP> nodeLog=new NodeLogAgent<>();
		nodeLog.setContext(context);
		c.accept(nodeLog);
		
		return flow.getNexts();
	}
	
}
